<template>
    <view class="container" v-if="showRegisterInfo" :style="themeColor">
        <view class="box">
            <view class="logo">
                <image v-if="logo" class="logo-img" :src="easyGetUserImgUrl(logo)"></image>
            </view>

            <view class="h5-box" :class="{ noMt: selectShopName }">
                <view v-if="selectShopName">
                    <text class="shop-name">{{ selectShopName }}</text>
                </view>
                <view class="card-group">
                    <card-cell-input
                        v-if="showRegisterInfo.RealName"
                        ref="RealName"
                        label="公司名称"
                        minWidth="100rpx"
                        placeholder="请输入公司名称"></card-cell-input>
                    <card-cell-input
                        v-if="showRegisterInfo.RealName"
                        ref="RealName"
                        label="联系人"
                        minWidth="100rpx"
                        placeholder="请输入联系人"></card-cell-input>
                </view>

                <view class="card-group region" v-if="showRegisterInfo.Region || showRegisterInfo.Address">
                    <view class="region-header" @click="getLocationInfo">
                        <text class="region-title">地址信息</text>
                        <text>{{ data.Latitude ? "已定位" : "未定位" }}</text>
                        <uni-icons type="arrowright"></uni-icons>
                    </view>
                    <view class="region-info" v-if="data.Latitude">
                        <text class="region-info-text">{{ regionName }}</text>
                        <textarea
                            class="cell-textarea"
                            placeholder="请填写详细地址(街道、楼牌号等)"
                            v-model="data.ContactAddress"></textarea>
                    </view>
                </view>
                <button class="btn btn-success btn-save" @click="register">注册</button>
                <!-- 	<view class="register-tip" @click="easyGoBack()">
					<text>已有账号，立即</text><text class="link-text">登录</text>
				</view> -->
            </view>
        </view>
        <view class="agreement" v-if="getAppSet().agreement">
            <label class="agrlabel" @click="selectFn(agreementchecked)">
                <checkbox
                    class="checkbox-mark"
                    :color="$store.state.themeColor"
                    style="transform: scale(0.7)"
                    :value="agreementchecked"
                    :checked="agreementchecked"></checkbox>
                <view class="color-dark">登录注册表示您已阅读并同意</view>
            </label>
            <view><text @click="agreement()">《用户协议》</text>和<text @click="privacy()">《隐私政策》</text></view>
        </view>
        <image class="loginBg" :src="easyGetImgUrl(loginBg)" v-if="loginBg" mode="aspectFill"></image>
        <!-- #ifdef MP -->
        <web-view class="webView" v-if="isShow" ref="webView" :src="url">
            <cover-view class="webView-mark" v-if="showNav"> </cover-view>
        </web-view>
        <!-- #endif -->
    </view>
</template>

<script>
import { mapMutations, mapState } from "vuex"
import cardCellInput from "@/components/common/cell/card-cell-input.vue"
import storage from "@/uni-sub-base/utils/storage.js"
import configAamap from "@/config/config.js"
import { getUserInfo, getProductDisplay } from "@/utils/appInit.js"
import { getUserCarList } from "@/utils/cartUtil.js"

import { getMemberDetail, judgeIsExist, batchSmartParse, UserLogin } from "@/service/api/member.js"
import { SubmitRegister } from "@/service/api/authorize.js"
import { GetRegisterInitData, getSmsNoVerifyCode } from "@/service/api/web.js"
import webViewUrl from "@/pages/micro/webViewUrl.js"
import { getPlatform } from "@/uni-sub-base/utils/platformUtil.js"
import { getLocation } from "@/uni-sub-base/utils/mapUtil.js"
import { mapbatchSmartParse } from "@/service/api/user.js"
export default {
    components: {
        cardCellInput,
    },
    data() {
        return {
            config: {
                back: false,
                barPlaceholder: false,
                backgroundColor: [0, "#ffffff"],
            },
            logo: "",
            loginBg: "",
            isShow: false,
            url: "",
            showNav: false,
            selectShopName: "",
            registerInfo: {},
            showRegisterInfo: null,
            memberList: [],
            registerGradeName: "",
            InvitUserPlaceholde: "请填写邀请人编号",
            selectGrade: {},
            sendText: "获取验证码",
            sendAble: true,
            registerFrom: null,
            data: {
                AddressName: "",
                ContactName: "",
                ContactTel: "",
                ContactAddress: "",
                IsDefault: false,
                ProvinceId: 0,
                ProvinceName: "",
                CityId: 0,
                CityName: "",
                AreaId: 0,
                AreaName: "",
                StreetId: 0,
                StreetName: "",
                Longitude: "",
                Latitude: "",
                ZipCode: null,
            },
            regionName: "",
            verCode: "",
            agreementchecked: false,
        }
    },
    onLoad(e) {
        if (e && e.selectShopName) {
            this.selectShopName = e.selectShopName
        }
    },
    mounted() {
        this.getWebInfo()
        this.getRegisterInitData()
    },
    methods: {
        ...mapMutations(["SET_AUTH"]),
        loginByService() {
            let userName = this.$refs.userName.getValue()
            let password = this.$refs.password.getValue()

            let param = {
                userName: userName,
                password: password,
            }
            let path = "?userName=" + userName + "&password=" + password
            UserLogin(param).then((res) => {
                if (res.State == 1) {
                    if (res.Data.State == 0) {
                        let token = res.Data.Token
                        this.goHome(token)
                    } else if (res.Data.State == 1) {
                        uni.hideLoading()
                        this.easyToast("您已提交注册申请，等待审核中")
                    } else {
                        uni.hideLoading()
                        this.easyToast(res.Data.StateName)
                    }
                } else {
                    uni.hideLoading()
                    this.easyToast(res.Msg)
                }
            })
        },
        selectFn(vaule) {
            this.agreementchecked = !this.agreementchecked
        },
        agreement() {
            this.easyGoTo("/pages/web/h5?url=https://mall.hct8090.com/m/home/AppIndex/2084")
        },
        privacy() {
            this.easyGoTo("/pages/web/h5?url=https://mall.hct8090.com/m/home/AppIndex/2085")
        },
        showLoginLoadding() {
            uni.showLoading({
                title: "注册中",
            })
        },
        changeImg() {},
        changeGrade(item) {
            this.selectGrade = item
            this.close()
        },
        close() {
            this.$refs.gradeNamePop.close()
        },
        openPop() {
            this.$refs.gradeNamePop.open()
        },
        goHome(token) {
            this.SET_AUTH(token)

            //#ifdef APP-PLUS
            if (getPlatform() == "ios") {
                let webInfo = storage.getCache("webInfo")
                if (webInfo) {
                    this.url =
                        webInfo.WebDomain +
                        (webInfo.AppHomeIndex ? webInfo.AppHomeIndex : webViewUrl.url.home) +
                        "?uniToken=" +
                        token
                }
                this.isShow = true
                setTimeout((e) => {
                    this.getUserInfo()
                }, 2500)
                getUserCarList()
                getProductDisplay().then((res) => {})
            } else {
                this.getUserInfo()
                getUserCarList()
                getProductDisplay().then((res) => {})
            }
            //#endif
            //#ifndef APP-PLUS
            let webInfo = storage.getCache("webInfo")
            if (webInfo) {
                this.url =
                    webInfo.WebDomain +
                    (webInfo.AppHomeIndex ? webInfo.AppHomeIndex : webViewUrl.url.home) +
                    "?uniToken=" +
                    token
            }
            this.isShow = true
            setTimeout((e) => {
                this.getUserInfo()
            }, 2500)
            getUserCarList()
            getProductDisplay().then((res) => {})
            //#endif
        },
        getUserInfo() {
            let url = "/pages/index/index"
            getUserInfo().then((res) => {
                uni.hideLoading()
                uni.reLaunch({
                    url: url,
                })
            })
        },
        saveUserInfo(data) {
            storage.setCache("userInfo", data)
        },
        getSMSCode() {
            let userName = this.$refs.userName.getValue()
            let password = this.$refs.password.getValue()
            let ImageVerifyCode = this.$refs.ImageVerifyCode.getValue()
            if (!userName) {
                this.easyToast("请输入手机号")
                return false
            }
            if (!password) {
                this.easyToast("请输入密码")
                return false
            }
            if (!ImageVerifyCode && this.registerInfo.ImageVerifyCode == 1) {
                this.easyToast("请输入图形验证码")
                return false
            }
            if (ImageVerifyCode != this.verCode && this.registerInfo.ImageVerifyCode == 1) {
                this.easyToast("请输入正确的图形验证码")
                return false
            }
            this.sendText = "正在发送中..."
            this.sendAble = false
            let param = {
                tel: userName,
                imgCode: ImageVerifyCode,
                validType: 8,
            }
            let path = "?tel=" + userName + "&imgCode=" + ImageVerifyCode + "&validType=8"
            getSmsNoVerifyCode(param, path).then((res) => {
                if (res.State) {
                    this.easyToast("验证码已发送，请查收")
                    storage.setCache("LastSendSmsTime", new Date()) //保存上次发送时间
                    this.setTimer()
                } else {
                    this.sendText = "获取验证码"
                    this.sendAble = true
                    this.easyToast(res.Msg)
                }
            })
        },
        setTimer() {
            const that = this
            let lastTime = this.getRemainSec()
            if (lastTime > 0) {
                clearInterval(that.timer)
                that.timer = setInterval(function () {
                    if (lastTime > 0) {
                        that.sendAble = false
                        that.sendText = "重新发送(" + lastTime + "s)"
                    } else {
                        that.sendAble = true
                        that.sendText = "重新发送"
                        clearInterval(that.timer)
                    }
                    lastTime--
                }, 1000)
            } else {
                storage.removeCache("LastSendSmsTime")
            }
        },
        getRemainSec() {
            let lastTime = storage.getCache("LastSendSmsTime")
            if (lastTime) {
                try {
                    let time = 60 - Math.ceil((new Date() - new Date(lastTime)) / 1000)
                    return time > 0 ? time : 0
                } catch (e) {}
            }
            return 0
        },
        register() {
            let userName = this.$refs.userName.getValue()
            let password = this.$refs.password.getValue()
            let ImageVerifyCode = 0,
                SMSVerifyCode = 0,
                InvitUser = 0,
                RealName = "",
                GradeId = this.selectGrade.ID || 0
            if (!userName) {
                this.easyToast("请输入手机号")
                return false
            }
            if (!password) {
                this.easyToast("请输入密码")
                return false
            }

            if (this.showRegisterInfo.RealName) {
                RealName = this.$refs.RealName.getValue()
                if (!RealName && this.registerInfo.RealName == 1) {
                    this.easyToast("请输入真实姓名")
                    return false
                }
            }

            if (this.showRegisterInfo.Region || this.showRegisterInfo.Address) {
                if (!this.data.Latitude) {
                    this.easyToast("请定位获取位置信息")
                    return false
                }
                if (this.showRegisterInfo.Address && !this.data.ContactAddress) {
                    this.easyToast("请输入详情地址")
                    return false
                }
            }

            if (this.showRegisterInfo.ImageVerifyCode) {
                ImageVerifyCode = this.$refs.ImageVerifyCode.getValue()
                if (ImageVerifyCode.trim() == "" && this.registerInfo.ImageVerifyCode == 1) {
                    this.easyToast("请输入图形验证码")
                    return false
                }
            }
            if (this.showRegisterInfo.SMSVerifyCode) {
                SMSVerifyCode = this.$refs.SMSVerifyCode.getValue()
                if (!SMSVerifyCode && this.registerInfo.SMSVerifyCode == 1) {
                    this.easyToast("请输入短信验证码")
                    return false
                }
            }

            if (!GradeId && this.memberList && this.memberList.length > 0) {
                this.easyToast("请选择会员等级")
                return false
            }

            if (this.showRegisterInfo.InvitUser) {
                InvitUser = this.$refs.InvitUser.getValue()
                if (!InvitUser && this.registerInfo.InvitUser == 1) {
                    this.easyToast("请输入邀请人编号")
                    return false
                }
            }
            if (!this.agreementchecked && this.getAppSet().agreement == true) {
                this.easyToast("请先同意《用户协议》和《隐私政策》")
                return
            }
            let user_name = userName
            let pwd = password
            let param = {
                GradeId: GradeId,
                InvitUserId: InvitUser,
                UserName: user_name,
                UserPsw: pwd,
                validType: 8,
                verifyCode: SMSVerifyCode,
                imgCode: ImageVerifyCode,
                provinceId: this.data.ProvinceId,
                cityId: this.data.CityId,
                regionId: this.data.AreaId,
                streetId: this.data.StreetId,
                provinceName: this.data.ProvinceName,
                cityName: this.data.CityName,
                regionName: this.data.AreaName,
                streetName: this.data.StreetName,
                address: this.data.ContactAddress,
                lat: this.data.Latitude ? this.data.Latitude : 0,
                lng: this.data.Longitude ? this.data.Longitude : 0,
                realName: RealName,
                DataIntegrityFlag: 1,
            }

            judgeIsExist(user_name).then((res) => {
                if (res.State == 1) {
                    this.showLoginLoadding()
                    SubmitRegister(param).then((data) => {
                        if (data.State == 1) {
                            if (data.Data.State == 0) {
                                this.easyToast("注册成功")
                                setTimeout((e) => {
                                    //接登录
                                    this.loginByService()
                                }, 800)
                            } else if (data.Data.State == 1) {
                                this.easyToast("您已提交注册申请，等待审核中")
                                setTimeout((e) => {
                                    this.easyGoBack()
                                }, 1500)
                            } else if (data.Data.State == 5) {
                                this.easyToast("您当前所在的区域未开放，请等待审核")
                                setTimeout((e) => {
                                    this.easyGoBack()
                                }, 1500)
                            }
                        } else {
                            uni.hideLoading()
                            this.easyToast(data.Msg)
                        }
                    })
                } else {
                    this.easyToast(res.Msg)
                }
            })
        },
        saveUserInfo(data) {
            storage.setCache("userInfo", data)
        },
        getWebInfo() {
            let webInfo = storage.getCache("webInfo")
            if (webInfo) {
                this.logo = webInfo.Logo
                this.loginBg = webInfo.LoginBackgroud
            }
        },
        disable(userName, password) {
            return userName.trim() == "" || password.trim() == ""
        },
        getRegisterInitData() {
            GetRegisterInitData().then((res) => {
                if (res.State == 1) {
                    this.memberList = res.Data.MemberGradeList
                    this.registerGradeName = "请选择" + res.Data.RegisterGradeName
                    if (res.Data.Infos && res.Data.Infos.length > 0) {
                        this.showRegisterInfo = {}
                        this.registerFrom = {}
                        res.Data.Infos.forEach((item) => {
                            this.showRegisterInfo[item.V_ItemParam] = item.IsDisplay
                            this.registerInfo[item.V_ItemParam] = item.IsRequired
                            this.registerFrom[item.V_ItemParam] = {
                                IsDisplay: item.IsDisplay,
                                IsRequired: item.IsRequired,
                            }
                        })
                    }
                    if (!this.registerInfo.InvitUser || this.registerInfo.InvitUser == 0) {
                        this.InvitUserPlaceholde = "请输入邀请人编号(选填)"
                    }
                }
            })
        },
        getLocationInfo() {
            //#ifdef MP-WEIXIN
            this.getCenterLocation()
            //#endif
            //#ifdef APP
            uni.navigateTo({
                url: "/pages_me/packet/map/map-poi",
                events: {
                    getSelectData: (data) => {
                        this.getAppP(data)
                        this.data.Longitude = data.location.longitude
                        this.data.Latitude = data.location.latitude
                        this.data.ContactAddress = data.name + data.address.replace(/\\/g, "")
                    },
                },
            })
            //#endif
            //#ifdef H5
            getLocation(
                (res) => {
                    if (res) {
                        this.data.ContactAddress = res.address.street + res.address.streetNum

                        this.getP(res.address)
                    }
                },
                (err) => {
                    console.log(err)
                },
            )
            //#endif
        },
        getCenterLocation() {
            var that = this
            wx.authorize({
                scope: "scope.userLocation",
                complete: function (res) {
                    wx.chooseLocation({
                        success(str) {
                            var getAddressUrl ='https://restapi.amap.com/v3/geocode/regeo?output=JSON&location='+str.longitude+','+str.latitude +
                                "&key=" +configAamap.aMapKey.wx
                            wx.request({
                                url: getAddressUrl,
                                success: function (result) {
                                    var province = result.data.regeocode.addressComponent.province
                                    var city = result.data.regeocode.addressComponent.city
                                    var district = result.data.regeocode.addressComponent.district
                                    var address = result.data.regeocode.addressComponent.streetNumber.street+result.data.regeocode.addressComponent.streetNumber.number

                                    that.data.ContactAddress = address
                                    that.data.Longitude = str.longitude
                                    that.data.Latitude = str.latitude
                                    that.getmapP(
                                       result.data.regeocode.addressComponent,
                                       address
                                    )
                                },
                            })
                        },
                    })
                },
            })
        },
        getP(res) {
            let item = {
                ContactAddress: res.street + res.streetNum,
                ProvinceName: res.province,
                CityName: res.city,
                AreaName: res.district,
                StreeName: res.street,
                ContactName: this.data.ContactName || "aaa",
                ContactTel: this.data.ContactTel || "13300000000",
            }
            let list = []
            list.push(item)
            let param = {
                list: list,
            }
            this.batchSmartParse(param)
        },
        getAppP(res) {
            let item = {
                ContactAddress: res.address,
                ProvinceName: res.province,
                CityName: res.city,
                AreaName: res.district,
                ContactName: this.data.ContactName || "aaa",
                ContactTel: this.data.ContactTel || "13300000000",
            }
            let list = []
            list.push(item)
            let param = {
                list: list,
            }
            this.batchSmartParse(param)
        },
        getmapP(res,address) {
            let item = {
                ContactAddress: address,
                ProvinceName: res.province,
                CityName: res.city,
                AreaName: res.district,
                StreetName: res.township,
                ContactName: this.data.ContactName || "aaa",
                ContactTel: this.data.ContactTel || "13300000000",
            }
            let list = []
            list.push(item)
            let param = {
                list: list,
            }
            this.batchSmartParse(param)
        },
        //智能识别
        batchSmartParse(param) {
            batchSmartParse(param).then((res) => {
                if (res.Data && res.Data.list && res.Data.list.length > 0) {
                    let result = res.Data.list[0]
                    this.data.ProvinceId = result.ProvinceId
                    this.data.ProvinceName = result.ProvinceName
                    this.data.CityId = result.CityId
                    this.data.CityName = result.CityName
                    this.data.AreaId = result.AreaId
                    this.data.AreaName = result.AreaName
                    this.data.StreetId = 0
                    this.data.StreetName = ""
                    this.getRegionName()
                }
            })
        },
        getRegionName() {
            let line = "-"
            this.regionName = `${this.data.ProvinceName || ""}-${this.data.CityName || ""}${
                this.data.AreaName ? line + this.data.AreaName : ""
            }${this.data.StreetName ? line + this.data.StreetName : ""}`
        },
        changeCode(e) {
            this.verCode = e
        },
    },
}
</script>

<style lang="scss">
.container {
    padding: 0 60rpx;
}

.btn-save {
    margin-top: 50rpx;
    height: 88rpx;
    font-size: $font-size-36;
}

.logo {
    display: flex;
    justify-content: center;
    height: 100rpx;
    margin-bottom: 10rpx;

    .logo-img {
        width: 100rpx;
        height: 100rpx;
        border-radius: $border-radius-10;
        box-shadow: 0rpx 0rpx 30rpx rgba($color-black, 0.1);
    }
}

.h5-box {
    margin-top: 100rpx;

    .link-box {
        display: flex;
        flex-direction: row;
        height: 60rpx;
        justify-items: center;

        .change-type {
            display: flex;
            flex: 1;
            color: $app-color-text-tip;
        }

        .forget-pwd {
            display: flex;
            flex: 1;
            justify-content: flex-end;
            color: $app-color-text-tip;
        }
    }

    .register-tip {
        margin: 30rpx 0;
        display: flex;
        justify-content: center;

        .link-text {
            color: $app-color-main;
        }
    }
}

.box {
    position: relative;
    z-index: 9;
    padding-top: 140rpx;
}

.loginBg {
    width: 100%;
    height: 100%;
    position: absolute;
    top: 0;
    let: 0;
    right: 0;
    bottom: 0;
    z-index: 0;
}

.card-group {
    border-radius: 20rpx;

    .card-group-cell {
        padding-top: 20rpx;
        padding-bottom: 20rpx;

        &:last-child {
            border-bottom: none;
        }
    }
}

.region {
    padding: 0 20rpx;

    .cell-textarea {
        height: 100rpx;
        color: #323232;
        font-size: $font-size-28;
        margin-bottom: 14rpx;
    }

    .region-header {
        height: 100rpx;
        display: flex;
        flex-direction: row;
        align-items: center;

        .region-title {
            flex: 1;
        }
    }

    .region-info-text {
        display: flex;
        font-size: $font-size-28;
        margin-bottom: 14rpx;
    }
}

.disable {
    opacity: 0.5;
    border: none;
}

.webView-mark {
    width: 100vw;
    height: 100vh;
    background: #fff;
    position: fixed;
    z-index: 999999999999;
    left: 0;
    right: 0;
    top: 0;
    bottom: 0;
    display: flex;
    justify-content: center;
}

.shop-name {
    display: flex;
    font-size: $font-size-40;
    margin-bottom: 40rpx;
    justify-content: center;
}

.noMt {
    margin-top: 0;
}

.bottom-list-box {
    background: $color-white;
    text-align: center;
    border-radius: 20rpx 20rpx 0 0;
    overflow: auto;

    .title {
        font-size: 28rpx;
        padding: 28rpx 0 40rpx;
        background: $uni-bg-color-grey;
        position: relative;

        &:after {
            content: "";
            position: absolute;
            width: 120rpx;
            height: 2rpx;
            background: $color-main;
            bottom: 28rpx;
            left: calc(50% - 60rpx);
        }
    }

    .list-box {
        max-height: 700rpx;
        overflow-y: auto;

        .item {
            padding: 30rpx 0;
            margin: 0 30rpx;

            &:not(:last-child) {
                border-bottom: 2rpx solid $uni-border-color;
            }

            .pay-img {
                width: 60rpx;
                height: 60rpx;
                margin-right: 30rpx;
            }

            .item-text {
                font-size: 28rpx;

                .balance {
                    font-size: 24rpx;
                    color: $color-gray-3;
                    margin-left: 20rpx;
                }
            }
        }
    }

    .button {
        margin: 60rpx 40rpx;
        font-size: 36rpx;
        line-height: 88rpx;
        letter-spacing: 8rpx;
        background: $color-main;
        border-radius: 12rpx;
        color: $color-white;
    }
}
.agreement {
    position: fixed;
    width: 100%;
    left: 0;
    bottom: 70rpx;
    display: flex;
    justify-content: center;
    align-items: center;
    .agrlabel {
        display: flex;
        justify-content: flex-start;
        align-items: center;
    }
    view {
        font-size: 24rpx;
        text {
            color: #eb1010 !important;
        }
    }
}
</style>
